<?php
namespace System\Core;

class Cache {
    protected $path;
    
    public function __construct() {
        $this->path = BASE_PATH . '/storage/cache/';
        if (!is_dir($this->path)) {
            mkdir($this->path, 0755, true);
        }
    }
    
    public function get($key, $default = null) {
        $file = $this->path . md5($key);
        
        if (!file_exists($file)) return $default;
        
        $content = file_get_contents($file);
        $data = unserialize($content);
        
        if ($data['expire'] > 0 && $data['expire'] < time()) {
            unlink($file);
            return $default;
        }
        
        return $data['value'];
    }
    
    public function set($key, $value, $seconds = 3600) {
        $file = $this->path . md5($key);
        $data = [
            'value' => $value,
            'expire' => $seconds > 0 ? time() + $seconds : 0
        ];
        
        return file_put_contents($file, serialize($data));
    }
    
    public function delete($key) {
        $file = $this->path . md5($key);
        if (file_exists($file)) {
            return unlink($file);
        }
        return false;
    }
}